<template>
  <div class="full-box">
    <div class="user-profile">
      <el-card class="profile-card">
        <template #header>
          <!-- 返回主页按钮 -->
          <div class="back-home">
            <el-button @click="goHome" type="text">< 返回主页</el-button>
          </div>
          <div class="card-header">
            <h2>个人中心</h2>
          </div>
        </template>

        <el-descriptions title="个人信息" :column="1" border>
          <el-descriptions-item label="用户姓名">{{
            userInfo.username
          }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{
            userInfo.email
          }}</el-descriptions-item>
          <el-descriptions-item label="单位">{{
            userInfo.address
          }}</el-descriptions-item>
          <el-descriptions-item label="手机号码">{{
            userInfo.phone
          }}</el-descriptions-item>
          <!-- 添加上传作品情况 -->
          <el-descriptions-item label="上传作品情况">{{
            uploadStatus
          }}</el-descriptions-item>
        </el-descriptions>

        <!-- 底部操作按钮区域 -->
        <div class="profile-actions">
          <el-button type="primary" @click="openPasswordDialog">
            修改密码
          </el-button>
          <el-button type="danger" @click="logout"> 退出登录 </el-button>
        </div>
      </el-card>

      <!-- 修改密码弹窗 -->
      <el-dialog title="修改密码" v-model="passwordDialogVisible" width="400px">
        <el-form
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordRules"
          label-width="100px"
        >
          <el-form-item label="旧密码" prop="oldPassword">
            <el-input
              v-model="passwordForm.oldPassword"
              type="password"
              show-password
            />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input
              v-model="passwordForm.newPassword"
              type="password"
              show-password
            />
          </el-form-item>
          <el-form-item label="确认新密码" prop="confirmPassword">
            <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              show-password
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updatePassword">提交</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { useMapMutations } from "@/store/index.js";
import { getUsersuploadedFiles } from "@/utils/api/File.js";

// 用户信息
const key = "userInfo";
const userInfo = JSON.parse(localStorage.getItem(key));
let { swithAuth } = useMapMutations({
  moduleName: "user",
  mapper: ["swithAuth"],
});
const uploadStatus = ref("")

// 控制修改密码弹窗
const passwordDialogVisible = ref(false);

// 密码表单数据
const passwordForm = reactive({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

// 表单校验规则
const passwordRules = {
  oldPassword: [{ required: true, message: "请输入旧密码", trigger: "blur" }],
  newPassword: [{ required: true, message: "请输入新密码", trigger: "blur" }],
  confirmPassword: [
    { required: true, message: "请确认新密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error("两次输入的新密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

const getUploadStatus = async () => {
  const res = await getUsersuploadedFiles(userInfo.id);
  const resLength = res.length;
  if (resLength > 0) {
    uploadStatus.value = `已上传${resLength}个作品`;
  } else {
    uploadStatus.value = "暂无作品上传";
  }
};

// 打开修改密码弹窗
const openPasswordDialog = () => {
  passwordDialogVisible.value = true;
};

// 提交修改密码请求
const updatePassword = async () => {
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    ElMessage.error("新密码与确认密码不一致");
    return;
  }

  try {
    const response = await axios.post("/api/user/update-password", {
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
    });

    if (response.data.success) {
      ElMessage.success("密码修改成功");
      passwordDialogVisible.value = false;
    } else {
      ElMessage.error(response.data.message || "修改失败");
    }
  } catch (error) {
    ElMessage.error("修改密码失败，请稍后重试");
  }
};

// 退出登录
const router = useRouter();
const logout = () => {
  localStorage.removeItem(key); // 清除用户信息
  swithAuth();
  ElMessage.success("退出成功");
  router.push("/"); // 跳转到登录页
};

// 跳转到主页
const goHome = () => {
  router.push("/");
};

onMounted(() => {
  getUploadStatus();
});
</script>

<style scoped lang="less">
@import "../assets/main.less";

.full-box {
  padding-top: @headerHeight;
  min-height: 100vh;
  height: 100vh;
  .m-bg;
}

.user-profile {
  max-width: 600px;
  margin: 50px auto;
}

.profile-card {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.back-home {
  margin: 10px;
}

/* 按钮底部区域样式 */
.profile-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}
</style>
